//
// Created by A on 2022/10/22.
//

#ifndef LOUTINE_GMP_H
#define LOUTINE_GMP_H


#include "switch.h"
#include "priority_queue.h"
#include "time_sched.h"
#include "deque.h"
#include <pthread.h>
#include <stdatomic.h>

# define G Loutine
# define STEAL_RATIO 0.25
# define MIN_STEAL_NUM 5
#define HARD_MAX_P 20

typedef struct M {
    struct P *related_p;

    pthread_mutex_t mutex;
    pthread_cond_t cond;
} M;


typedef struct P {
    volatile bool is_busy;
    volatile M *attached_m;
    priority_queue *pq;
    Loutine *cur;
} P;


typedef struct m_running_arg {
    M *self;
    void *stack;
} m_running_arg;

typedef struct gmp_env {

    deque global_queue;

    // 全局队列的同步工具
    pthread_mutexattr_t shared_mutex_arg;
    pthread_mutex_t global_queue_mutex;

    int max_p;
    P *plist;
    M *mlist;
    m_running_arg *m_arg_list;

    int tid_map_list[HARD_MAX_P * 2];
} gmp_env;


extern gmp_env *env;


void execute_daemon_thread();

void init_p(P *p);

void init_m(M *m);

P *create_p();

//void set_max_p(int max_p);

int get_max_p();


#endif //LOUTINE_GMP_H
